package com.woniu.tmsorder.listener;


import com.woniu.tmsorder.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.Topic;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
    @Resource
    private OrderService orderService;
    // 配置监听哪个频道
    private static final Topic KEYEVENT_EXPIRED_TOPIC = new PatternTopic("__keyevent@0__:expired");

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    protected void doRegister(RedisMessageListenerContainer listenerContainer) {
        // 频道可以是多个，多个传list
        listenerContainer.addMessageListener(this,KEYEVENT_EXPIRED_TOPIC);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 用获取失效的key
        String expiredKey = message.toString();
        System.out.println(expiredKey);
        // 判断
        if (expiredKey.startsWith("order_info_")){
            String orderNo = expiredKey.split("_")[2];
            orderService.updateOrderStatusByOrderNo(orderNo);
        }
    }
}